<template>
  <form-dialop
    :title="$t('desktopManage.operation.bindClient')"
    :visible="visible"
    width="35%"
    @handleClose="handleClose"
		v-loading="loading"
  >
  <template #name>
    <span class="tips">{{$t('desktopManage.bindClientTitleTips')}}</span>
  </template>
    <template #content>
      <div style="padding-top: 30px;">
        <el-form ref="form" :model="subData" label-position="right" :rules="formRules">
          <el-form-item :label="$t('objectType.desktop_client')" prop="hw_ids" name="hw_ids">
            <el-select v-model="subData.hw_ids" value-key="hardware_id" :multiple-limit="selectLimit" collapse-tags medium style="width:130%" multiple  clearable remote :remote-method="remoteMethod" @keyup.enter.native="submit" filterable>
              <el-option
                v-for="client in clientList"
                :key="client.hardware_id"
                :label="client.name"
                :value="client"
                :disabled="client.in_cloud_tenant == false">
                <el-tooltip class="item" effect="dark" :disabled="isDisable(client)" :content="$t('desktopManage.maxBindClientTips')" placement="right">
                  <div style="float: left; width:calc(100% + 20px); padding-right:20px">
                    {{ client.name }}
                    <span style="color: #cccc;"> {{ client.hardware_id }} </span>
                    <span style="float: right; color: #8492a6; font-size: 12px;magin-left:2px"  v-show="client.in_cloud_tenant == false">{{$t('desktopManage.bindTips2')}}</span>
                  </div>
                </el-tooltip>
              </el-option>
              <el-pagination
                class="pagination"
                small
                @current-change="handleCurrentChange"
                :current-page.sync="currentPage"
                :page-size="5"
                layout="prev, pager, next, jumper"
                :total="currentTotal">
              </el-pagination>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </template>
    <template #footer>
      <el-button @click="handleClose">{{ $t('common.cancel') }}</el-button>
      <el-button type="primary" @click="submit" :disabled="loading">{{ $t('common.confirm') }}</el-button>
    </template>
  </form-dialop>
</template>
<script lang="ts">
import Vue from 'vue'
import FormDialop from '@/components/Dialog/formDialog.vue';
import { AppModule } from '@/store/modules/app'
export default Vue.extend({
  components: {
    FormDialop
  },
  data() {
    return {
      visible: false,
      loading: false,
      formData: '',
      language: AppModule.language,
      subData: {
        hw_ids: []
      },
      clientList: [],
      currentPage: 1,
      currentTotal: 0,
      searchValue: '',
      selectLimit: 5,
      oldBind: [],
      formRules: {
        hw_ids: [
          { required: true, message: (this as any).$t('objectType.desktop_client_error'), trigger: 'blur' },
        ]
      }
    }
  },
  computed: {
    isDisable() {
      return (client: any) => {
        if(this.subData.hw_ids.length != this.selectLimit) {
          return true;
        } else {
          for(let i in (this as any).subData.hw_ids) {
            if(client.in_cloud_tenant == false) {
              return true;
            }
            if(client.hardware_id == (this as any).subData.hw_ids[i].hardware_id) {
              return true;
            }
          }
          return false;
        }
      }
    }
  },
  methods: {
    async init(row: any) {
      this.formData = JSON.parse(JSON.stringify(row));
      this.oldBind = JSON.parse(JSON.stringify((this as any).formData.bind_clients));
      await this.$pandaApi.apiGetMeshSettings().then((res: any) => {
        this.selectLimit = res.max_binding_client_num
      });
      this.currentPage = 1;
      this.clientList = [];
      this.subData.hw_ids = [];
      for(let i in (this as any).formData.bind_clients) {
        if((this as any).formData.bind_clients[i].in_cloud_tenant != false) {
          (this as any).subData.hw_ids.push((this as any).formData.bind_clients[i]);
        }
      }
      this.getClientList();
      this.$nextTick(() => {
        if (this.$refs['form']) {
          (this.$refs['form'] as any).clearValidate();
        }
      })
      this.visible = true;
    },
    remoteMethod(params: any) {
      this.searchValue = params;
      this.getClientList();
    },
    getClientList() {
      this.$pandaApi.apiGetClientListByPageSize(this.currentPage, 5, (this as any).formData.cloud_tenant_id, this.searchValue).then((res: any) => {
        this.currentTotal = res.total;
        this.clientList = [];
        // (this as any).formData.bind_clients = [];
        // (this as any).formData.bind_clients = JSON.parse(JSON.stringify((this as any).oldBind))
        for(let j in (this as any).formData.bind_clients) {
          if((this as any).formData.bind_clients[j].in_cloud_tenant == false) {
            (this as any).clientList.unshift((this as any).formData.bind_clients[j]);
          }
        }
        for(let i in res.rows) {
          (this as any).clientList.push({
            "hardware_id": res.rows[i].hardware_id,
            "in_cloud_tenant": 1,
            "name": res.rows[i].name,
          })
        }
        let name = 'hardware_id';
        let map = new Map();
        for (let item of (this as any).clientList) {
          if (!map.has(item.hardware_id)) {
            map.set(item.hardware_id, item);
          }
        }
        (this as any).clientList = [...map.values()];
        // for(let i in this.clientList) {
        //   let flag = 1;
        //   for(let j in (this as any).formData.bind_clients) {
        //     if((this as any).clientList[i].hardware_id == (this as any).formData.bind_clients[j].hardware_id) {
        //       (this as any).clientList[i].in_cloud_tenant = (this as any).formData.bind_clients[j].in_cloud_tenant
        //       // (this as any).clientList[i].in_cloud_tenant = false;
        //       flag = 0;
        //     }
        //   }
        //   if(flag == 1) {
        //     (this as any).formData.bind_clients.push({
        //       "hardware_id": (this as any).clientList[i].hardware_id,
        //       "in_cloud_tenant": 1,
        //       "name": (this as any).clientList[i].name,
        //     })
        //     (this as any).clientList.push({
        //       "hardware_id": (this as any).clientList[i].hardware_id,
        //       "in_cloud_tenant": 1,
        //       "name": (this as any).clientList[i].name,
        //     })
        //   }
        // }
        // this.clientList = JSON.parse(JSON.stringify((this as any).formData.bind_clients));
        // for(let i in (this as any).formData.bind_clients) {
        //   let flag = 1;
        //   for(let j in this.clientList) {
        //     if((this as any).clientList[j].hardware_id == (this as any).formData.bind_clients[i].hardware_id) {
        //       (this as any).clientList[j].in_cloud_tenant = (this as any).formData.bind_clients[i].in_cloud_tenant
        //       // (this as any).clientList[j].in_cloud_tenant = false;
        //       flag = 0;
        //     }
        //     // if((this as any).hasShownData.indexOf((this as any).clientList[j].hardware_id) != -1 && this.currentPage <= 1) {
        //     //   (this as any).clientList.splice(j,1)
        //     // }
        //   }
        //   if(flag == 1 && this.currentPage <= 1) {
        //     (this as any).clientList.unshift({
        //       "hardware_id": (this as any).formData.bind_clients[i].hardware_id,
        //       "in_cloud_tenant": (this as any).formData.bind_clients[i].in_cloud_tenant,
        //       "name": (this as any).formData.bind_clients[i].name,
        //     });
        //   }
        // }
        // console.log(this.clientList);
      })
    },
    handleCurrentChange(params: any) {
      this.getClientList()
    },
    submit() {
      (this.$refs.form as any).validate((valid: any) => {
        if (valid) {
          if(this.subData.hw_ids.length > this.selectLimit) {
            this.$message.warning((this as any).$t('desktopManage.bindNumberTips'));
            return ;
          }
          
					this.loading = true;
          let d = [];
          for(let i in (this as any).subData.hw_ids)  {
            if((this as any).subData.hw_ids[i].in_cloud_tenant != false) {
              d.push((this as any).subData.hw_ids[i].hardware_id)
            }
          }
          this.$pandaApi.apiPostDesktopBindClient((this as any).formData.id, {
            "hardware_ids": d
          }).then((res: any) => {
            if(res.code == 200) {
              this.$message.success((this as any).$t('desktopManage.bindClientSuccess'))
              this.$emit("success")
              this.handleClose();
            }
          }).catch(() => {
            this.$message.warning((this as any).$t('desktopManage.bindClientFail'))
            this.loading = false;
          })
        }
      });
    },
    handleClose() {
      this.visible = false;
      this.searchValue = "";
			this.loading = false;
    }
  }
})
</script>
<style lang="scss" scoped>
.pagination {
  ::v-deep.el-pager {
    font-weight: normal;
  }
  ::v-deep.el-pagination__editor {
    line-height:22px !important;
    height:22px !important;
  }
}
.tips {
  font-size: 12px;
  color: gray;
  margin-left: 10px;
  width: 75%;
}
</style>
